import { Radio, Tooltip } from 'antd';
import moment from 'moment';
import React from 'react';
import { JSONObject } from 'admin/schema/common';
import {
  SessionCenterConfigInfo,
  SessionCenterGraphInfo,
  SessionCenterTableInfo,
} from 'admin/schema/RealTimeMonitor';
import {
  getSCConfigList,
  getSCGraphData,
  getSCTableData,
  modifySCConfig,
} from 'admin/servers/servers';
import { clearNull } from 'utils/tools';
import '../style.scss';
import { BaseMonitor, BaseMonitorProp } from './BaseComponent';

export class SessionMonitor extends BaseMonitor {
  constructor(prop: BaseMonitorProp) {
    super(prop);
    this.title = 'Session Center监控';
    this.btnCaption = '+新增Session Center';
    this.layout = [3.6, 6];
    this.tickCount = 5;
    this.seriesField = 'scName';
    this.permissionType = '/systemMonitor/realTimeMonitor/sessionCenter';
    const verifyFunc = (val: string | number) => {
      const verifyNumber = !isNaN(val as number);
      let verifySum = false;
      let verifyFormat = false;
      if (verifyNumber) {
        val > 0 && (verifySum = true);
      }
      !val.toString().startsWith('0') && (verifyFormat = true);
      return verifyNumber && verifySum && verifyFormat;
    };
    this.formConfig = [
      {
        name: 'Session Center名称',
        key: 'scName',
      },
      {
        name: '会话阈值',
        key: 'scThreshold',
        verify: verifyFunc,
      },
      {
        name: 'Caps阈值',
        key: 'scCapsThreshold',
        verify: verifyFunc,
      },
    ];
    this.state = {
      mode: prop.mode,
    };
  }

  protected getGraphDataReq(): Promise<SessionCenterGraphInfo[]> {
    return new Promise(resolve => {
      const mode = this.state.mode;
      const isHistory = mode === 'history';
      const isYeaterday = this.realTimeTarget === 5;
      const data = {
        beginTime: isHistory ? this.historyDate : this.realTimeDate,
        endTime: isHistory
          ? moment().format('YYYY-MM-DD') + ' 00:00:00'
          : moment().format('YYYY-MM-DD HH:mm:ss'),
        interval: isHistory || isYeaterday ? 60 : void 0,
      };
      getSCGraphData(this.currentItemName, clearNull(data))
        .then(res => {
          !res.data && resolve([]);
          const result: SessionCenterGraphInfo[] = [];
          const data = res.data;
          const len = data.length;
          for (let i = 0; i < len; i++) {
            const item = data[i];
            item.time = moment(item.time).format(isHistory ? 'HH:mm' : 'HH:mm:ss');
            item.scName = '会话';
            const capsData: JSONObject = {};
            capsData.scName = 'caps';
            capsData.value = item.capsValue;
            capsData.time = moment(item.capsTime).format(isHistory ? 'HH:mm' : 'HH:mm:ss');
            result.push(capsData as SessionCenterGraphInfo, item);
          }
          resolve(result);
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  protected getTableDataReq(): Promise<SessionCenterTableInfo[]> {
    this.refreshRealTime();
    return new Promise(resolve => {
      const isHistory = this.state.mode === 'history';
      const data = {
        beginTime: isHistory ? this.historyDate : this.realTimeDate,
        endTime: isHistory
          ? moment().format('YYYY-MM-DD') + ' 00:00:00'
          : moment().format('YYYY-MM-DD HH:mm:ss'),
      };
      getSCTableData(data)
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  protected getIndicatorsReq(): Promise<SessionCenterConfigInfo[]> {
    return new Promise(resolve => {
      getSCConfigList()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  protected modifyIndicatorsReq(params: SessionCenterConfigInfo[]): Promise<void> {
    return new Promise(resolve => {
      modifySCConfig(params).then(() => {
        resolve();
      });
    });
  }

  protected renderTable(): JSX.Element {
    const data = this.tableData as SessionCenterTableInfo[];
    if (!data) {
      return <></>;
    }
    const { currentItemName } = this;
    let realTimeSum = 0;
    let alarmSun = 0;
    let capsRealTimeSum = 0;
    let capsAlarmSum = 0;
    data.forEach(item => {
      realTimeSum += item.realTimeCount;
      alarmSun += item.alarmCount;
      capsRealTimeSum += item.capsRealTimeCount;
      capsAlarmSum += item.capsAlarmCount;
    });

    return (
      <div className="monitor-sc-table">
        <div className="monitor-sc-tableheader">
          <div className="monitor-sc-tablecol" id="sc-firstcol"></div>
          <div className="monitor-sc-tablecol">最大会话数</div>
          <div className="monitor-sc-tablecol">最小会话数</div>
          <div className="monitor-sc-tablecol">平均会话数</div>
          <div className="monitor-sc-tablecol">实时会话数</div>
          <div className="monitor-sc-tablecol">会话阈值</div>
          <div className="monitor-sc-tablecol">告警数</div>
          <div className="monitor-sc-tablecol">最大caps数</div>
          <div className="monitor-sc-tablecol">最小caps数</div>
          <div className="monitor-sc-tablecol">平均caps数</div>
          <div className="monitor-sc-tablecol">实时caps数</div>
          <div className="monitor-sc-tablecol">caps阈值</div>
          <div className="monitor-sc-tablecol">告警数</div>
        </div>
        <div className="monitor-sc-tablebody">
          {data.map((item, index) => {
            return (
              <div className={`monitor-sc-row ${!item.onLine && 'offline'}`} key={index}>
                <div className="monitor-sc-tablecol" id="sc-firstcol">
                  <Tooltip title={item.scName}>
                    <Radio
                      checked={currentItemName === item.scName}
                      onChange={e => {
                        this.handleCurrentItemNameChange(e, item.scName);
                      }}
                    />
                    {item.scName}
                  </Tooltip>
                </div>
                <div className="monitor-sc-tablecol">{item.maxCount}</div>
                <div className="monitor-sc-tablecol">{item.minCount}</div>
                <div className="monitor-sc-tablecol">{item.average}</div>
                <div className="monitor-sc-tablecol">{item.realTimeCount}</div>
                <div className="monitor-sc-tablecol">{item.threshold}</div>
                <div className="monitor-sc-tablecol">{item.alarmCount}</div>
                <div className="monitor-sc-tablecol">{item.capsMaxCount}</div>
                <div className="monitor-sc-tablecol">{item.capsMinCount}</div>
                <div className="monitor-sc-tablecol">{item.capsAverage}</div>
                <div className="monitor-sc-tablecol">{item.capsRealTimeCount}</div>
                <div className="monitor-sc-tablecol">{item.capsThreshold}</div>
                <div className="monitor-sc-tablecol">{item.capsAlarmCount}</div>
              </div>
            );
          })}
        </div>
        <div className="monitor-sc-tablefooter">
          <div className="monitor-sc-tablecol monitor-table-sum" id="sc-firstcol">
            总计
          </div>
          <div className="monitor-sc-tablecol"></div>
          <div className="monitor-sc-tablecol"></div>
          <div className="monitor-sc-tablecol"></div>
          <div className="monitor-sc-tablecol">{realTimeSum}</div>
          <div className="monitor-sc-tablecol"></div>
          <div className="monitor-sc-tablecol">{alarmSun}</div>
          <div className="monitor-sc-tablecol"></div>
          <div className="monitor-sc-tablecol"></div>
          <div className="monitor-sc-tablecol"></div>
          <div className="monitor-sc-tablecol">{capsRealTimeSum}</div>
          <div className="monitor-sc-tablecol"></div>
          <div className="monitor-sc-tablecol">{capsAlarmSum}</div>
        </div>
      </div>
    );
  }
}
